<template>
  <main class="h-[calc(100vh-100px) ]" v-loading="loading" element-loading-background="#05051a">
    <div class="px-[24px] py-4 gridBox">
      <div v-for="(item, index) in list" :key="index" class="max-w-[600px]">
        <CommonCard
          :title="`${item.no}  ${getName(item.name)}`"
          isShowRight
          :info="item"
          isShowStatus
          :rightCtn="`(${item?.sex == '1' ? '男' : item?.sex == '2' ? '女' : '未知'}/${item.age})`"
        >
          <template #content>
            <div v-if="item.tabList && item.tabList.length > 0" class="h-[310px]">
              <TabBox :tab-list="item.tabList" :extraInfo="item" @tabHandle="tabHandle" />
              <div v-if="item.tabActive === '2'" class="w-full">
                <BloodPressure :familyId="item.id" />
              </div>
            </div>
          </template>
        </CommonCard>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="" width="98vw" destroy-on-close align-center>
      <BloodPressureDetails />
    </el-dialog>
    <transition name="el-fade-in-linear">
      <div class="centerBox" v-if="useCommonStore().isSearchHide">
        <CommonCard title="我要搜索">
          <template #content>
            <div class="w-[350px]">
              <input
                class="bg-[#09183d] p-2 w-full searchInput"
                type="text"
                placeholder="立即搜索"
                v-model="formData.name"
              />
              <div class="flex justify-between mt-3">
                <div
                  class="w-[48%] border border-[#5191f6] text-center py-2 cursor-pointer"
                  @click="cancelFn"
                >
                  取消
                </div>
                <div class="w-[48%] bg-[#5191f6] text-center py-2 cursor-pointer" @click="searchFn">
                  确认
                </div>
              </div>
            </div>
          </template>
        </CommonCard>
      </div>
    </transition>
  </main>
</template>
<script lang="ts" setup>
import BloodPressureDetails from './bloodPressDetails.vue'
import CommonCard from '@/components/CommonCard.vue'
import BloodPressure from './component/BloodPressure.vue'
import TabBox from '@/components/TabBox.vue'
import { onActivated, onMounted, onUnmounted, ref, watch } from 'vue'
import { timeNum, nameHide } from '@/utils/commonFn'
import { familyList, getFamilyDeviceType, getWarningCount } from '@/api/home'
import { useCommonStore } from '@/stores/common'
import { usePatientStore } from '@/stores/patient'
import router from '@/router'
const timer = ref()
const totalpage = ref()
const isRefreshLock = ref()
const loading = ref(false)
const dialogVisible = ref(false)
const formData = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  institutionId: sessionStorage.getItem('institutionId')
})
const list = ref<any[]>([])
const getName = (name: string) => {
  const isNameHide = useCommonStore().isNameHide
  if (isNameHide) {
    return nameHide(name)
  } else {
    return name
  }
}
const searchFn = () => {
  formData.value.pageNum = 1
  list.value = []
  getApiData(formData.value)
  useCommonStore().setIsSearchHide()
}
watch(
  () => useCommonStore().institutionId,
  (value) => {
    formData.value.institutionId = value
    formData.value.pageNum = 1
    list.value = []
    getApiData(formData.value)
  }
)
const cancelFn = () => {
  formData.value.name = ''
  useCommonStore().setIsSearchHide()
}
onMounted(() => {
  loading.value = true
  getApiData(formData.value)
  timer.value = setInterval(async () => {
    formData.value.pageNum = 1
    list.value = []
    getApiData(formData.value)
  }, timeNum)
  window.addEventListener('scroll', windowScroll, true) //监听滚动条事件
})
// 监听滚动条，获取数据
const windowScroll = () => {
  // console.log(e)
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  //可视区的高度
  let windowHeight = document.documentElement.clientHeight || document.body.clientHeight
  //滚动条的总高度
  let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
  //滚动条到底部的条件
  if (scrollTop + windowHeight >= scrollHeight - 200 && isRefreshLock.value == true) {
    if (totalpage.value >= formData.value.pageNum) {
      // false防止多次触发加载数据
      isRefreshLock.value = false
      getApiData(formData.value)
    }
  }
}

// 获取接口数据
const getApiData = async (params2: any) => {
  const res: any = await familyList(formData.value)
  for (let index = 0; index < res.rows.length; index++) {
    const item = res.rows[index]
    const res1 = await getFamilyDeviceType({ familyId: item.id })
    item.tabList = []
    res1?.data.forEach((i: any) => {
      if (i.deviceType === 1) {
        item.tabList.push({
          value: '1',
          name: '心电设备'
        })
      }
      if (i.deviceType === 2) {
        item.tabList.push({
          value: '2',
          name: '血压设备'
        })
        item.serviceEndDate = i.serviceEndDate
      }
      if (i.deviceType === 3) {
        item.tabList.push({
          value: '3',
          name: '血糖设备'
        })
      }
      if (i.deviceType === 4) {
        item.tabList.push({
          value: '4',
          name: '睡眠设备'
        })
      }
      if (i.deviceType === 5) {
        item.tabList.push({
          value: '5',
          name: '防跌倒设备'
        })
      }
      if (i.deviceType === 6) {
        item.tabList.push({
          value: '6',
          name: '血氧设备'
        })
      }
      item.tabActive = item.tabList[0].value
    })
    const res2 = await getWarningCount({ familyId: item.id })
    item.isWarning = res2?.data
  }
  totalpage.value = Math.ceil(res.total / formData.value.pageSize)

  if (res.total == 0) {
    console.log('无数据 处理逻辑')
    isRefreshLock.value = true
  } else {
    if (totalpage.value >= params2.pageNum) {
      console.log('加载下一页')
      list.value = [...list.value, ...res.rows]
      console.log(list.value)
      //加载数据可以触发
      isRefreshLock.value = true
      //返回数据后页码加一
      formData.value.pageNum += 1
    } else {
      console.log('不够一页')
      list.value = res.rows
    }
    //加载数据可以触发
    isRefreshLock.value = true
  }
  loading.value = false
}

onUnmounted(() => {
  clearInterval(timer.value)
})
const tabHandle = (e: CommonTypes.tabList, info: any) => {
  info.tabActive = e.value
  usePatientStore().setPatientBPInfo(info)
  // router.push(`/bloodPressDetails`)
  dialogVisible.value = true
}
</script>

<style scoped lang="less">
.gridBox {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(520px, 1fr)); /* 自适应列布局 */
  gap: 10px; /* 子元素之间的间距 */
}
.centerBox {
  background: #08102b;
  position: fixed;
  left: 50%;
  top: 40%;
  transform: translate(-50%, -50%);
  z-index: 999;
}
.searchInput {
  border: 2px solid #16203e;
  outline: none;
}
:deep(.el-dialog) {
  padding: 0px !important;
}
:deep(.el-dialog__header) {
  padding: 0px !important;
}
:deep(.el-overlay-dialog) {
  overflow: hidden !important;
}
:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #fff !important;
}
</style>
